package com.kk.quyan.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kk.quyan.dao.LabelMapper;
import com.kk.quyan.entity.Label;
import com.kk.quyan.entity.Material;
import com.kk.quyan.dao.MaterialMapper;
import com.kk.quyan.service.MaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kk.quyan.utils.excelUtil.ExcelData;
import com.kk.quyan.utils.excelUtil.ExcelListener;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 素材表 服务实现类
 * </p>
 *
 * @author kk
 * @since 2020-11-21
 */
@Service
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, Material> implements MaterialService {
    @Resource
    private MaterialMapper materialMapper;
    @Resource
    private LabelMapper labelMapper;

    //优化
    @Override
    public List<Material> getMaterials(int labelId, int page, int limit) {
        //统计该标签下的素材数量
        int count=materialMapper.countMaterialByLabelId(labelId);
        if (count==0){
            //若count为0，则直接返回
            return null;
        }else {
            //若count大于1，则获取结果集
            int startNum = (page - 1) * limit;
            List<Material> materials = materialMapper.selectMaterialByLabelId(labelId, startNum, limit);
            return materials;
        }
    }

    //递归查找
    @Override
    public int countMaterial(int labelId) {
        int count=0;
        Set<Label> results=new HashSet<>();
        List<Label> children = labelMapper.selectList(new QueryWrapper<Label>().eq("pid", labelId)
                .select("id"));
        if (children.size()==0||children==null){
            //说明为叶子标签
            count+=materialMapper.countMaterialByLabelId(labelId);
        }else {
            findChildren(children,results);
            Iterator<Label> iterator = results.iterator();
            while (iterator.hasNext()){
                count+=materialMapper.countMaterialByLabelId(iterator.next().getId());
            }
        }
        return count;
    }

    //DFS
    private void findChildren(List<Label> children, Set<Label> results) {
        for(Label label:children){
            //寻找叶子结点
            List<Label> son = labelMapper.selectList(new QueryWrapper<Label>().eq("pid", label.getId())
                    .select("id", "pid"));
            if (son.size()==0){
                //添加叶子结点标签
                results.add(label);
            }else {
                findChildren(son,results);
            }
        }
    }

    @Override
    public void saveExcel(MultipartFile file, MaterialService materialService) {
        try {
            InputStream in=file.getInputStream();
            //调用方法读取
            EasyExcel.read(in, ExcelData.class,new ExcelListener(materialService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void exportExcel(int type) {
        QueryWrapper<Material> queryWrapper=null;
        List<Material> materials=new ArrayList<>();
        if (type!=-1){
            queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("type",type);
        }
        materials=baseMapper.selectList(queryWrapper);

        String path = System.getProperty("user.dir");
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
        String n_date = dateFormat.format(new Date());
        String filePath=path+"\\excelFile\\";
        String fileName=n_date+".xlsx";
        //System.out.println(filePath);
        File file=new File(filePath+fileName);
        File dir=new File(filePath);
        if (!dir.exists()){
            dir.mkdir();
        }
        if (!file.exists()){
            try {
                System.out.println("create");
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        EasyExcel.write(file, Material.class).sheet("demo").doWrite(materials);
    }

    @Override
    public IPage<Material> getMaterialsByKeyword(String keyword, int pageNum, int limit) {
        Page<Material> page=new Page<>(pageNum,limit);
        IPage<Material> results = materialMapper.selectPage(page, new QueryWrapper<Material>()
                .like("title", keyword)
                .or()
                .like("description", keyword));
        return results;
    }
}
